/* eslint-disable no-param-reassign */
import { useRef, useState, useEffect, useCallback } from 'react';
import JRPCSocket from './json-rpc-websocket';

// TODO rewrite from zero

function useRPC(updateChartData, updateDataInformation, visible, callback) {
  const intervalBeatRef = useRef(null);
  const reconnectTimerRef = useRef(null);
  const JPRCtask = useRef({ socket: null, uri: null }).current;

  const [runState, setRunState] = useState(false);
  const [taskMessage, setTaskMessage] = useState(null);
  const [dataEndpoint, setDataEndpoint] = useState(null);

  const handleDataForChart = useCallback((data) => {
    const { receivable } = {};
    if (data) {
      data.dataCollection.forEach((item) => {
        if (item.type === 'fastTestData') {
          const {
            totalPoints,
            data: { antennaMeasure },
          } = item;
          if (totalPoints && antennaMeasure && totalPoints > antennaMeasure.length) {
            const undefs = [];
            for (let i = 0; i < totalPoints - antennaMeasure.length; i += 1) {
              undefs.push(undefined);
            }
            item.data.antennaGain = [...item.data.antennaGain, ...undefs];
            item.data.antennaMeasure = [...item.data.antennaMeasure, ...undefs];
            item.data.meter = [...item.data.meter, ...undefs];
            item.data.originMeter = [...item.data.originMeter, ...undefs];
            item.data.noiseTemperature = [...item.data.noiseTemperature, ...undefs];
            item.data.psd1 = [...item.data.psd1, ...undefs];
            item.data.psd2 = [...item.data.psd2, ...undefs];
            item.data.systemGain = [...item.data.systemGain, ...undefs];
          }
          // window.console.log('------------------------------------');
          // window.console.log(item.data.meter, item.data.originMeter);
          updateChartData(item.data.originMeter);
          callback?.(item);
          if (receivable) {
            updateDataInformation(item.data);
          }
        }
      });
    }
  }, []);

  const initTask = useCallback((url) => {
    JPRCtask.socket = new JRPCSocket({
      url,
      onopen: () => {
        clearInterval(intervalBeatRef.current);
        intervalBeatRef.current = setInterval(() => {
          window.console.log('heartbeat');
          JPRCtask.socket?.send?.({
            id: 1,
            method: 'heartbeat',
          });
        }, 3000);
      },
      onmessage: (res) => {
        if (res.params && res.params instanceof Object) {
          handleDataForChart(res.params);
        }
      },
      onerror: () => {
        window.console.log('error');
      },
      onclose: () => {
        window.console.log('close1', intervalBeatRef.current);
        if (intervalBeatRef.current) {
          clearInterval(intervalBeatRef.current);
          intervalBeatRef.current = null;
        }
      },
    });
  }, []);

  useEffect(() => {
    if (visible) {
      window.console.log('visible:√');
      initTask('ws://localhost');
    } else {
      window.console.log('visible:×');
    }
  }, [visible]);

  useEffect(() => {
    const { uri } = dataEndpoint || {};
    JPRCtask.uri = uri;
    if (uri) {
      const { socket } = JPRCtask;
      socket ? socket.withUrl(uri) : initTask(uri);
    } else {
      window.console.log('没有连接地址');
    }
  }, [JSON.stringify(dataEndpoint)]);

  useEffect(() => {
    return () => {
      window.console.log('exit');
    };
  }, []);

  return {
    JPRCtask,
    dataEndpoint,
    setDataEndpoint,
    taskMessage,
    setTaskMessage,
    runState,
    setRunState,
  };
}

export default useRPC;
